import React from 'react'
import {
  BaseListPage,
  IBaseListPageState,
  IBaseListPageProps,
  columnRenders,
  UdDateRangePicker,
  http,
  UdTable,
  UdModal,
  UdDrawer,
  uaaApp,
} from '@/lib'
import { Select, Spin, message, Modal, Badge, Button, Tooltip } from 'antd'

import apis from '@/apis/AboutQuota'
import udMainStore from '@/store/UdMain'
import './style.scss'
import { WithToolbar } from '@/components/PhotoView'
import quotaApis from '@/apis/AboutQuota'
import { downBlobFileXlsx } from '@/utils/methods'
import ImportExcel from '../components/ImportExcel'
import EditCheckStockDetail from '../components/EditCheckStockDetail'
import AddStockFormModal from '../components/AddStockFormModal'
import StocksApprovalProcess from '../components/StocksApprovalProcess'
import AddCheckStockDetail from '../components/AddCheckStockDetail'
const deleteBtnAuthAll = 'quota_employee_manager_delCheckStocks'
const deleteBtnAuth = 'quota_employee_manager_delCheckStockDetails'
const editBtnAuth = 'quota_employee_manager_editCheckStockDetails' //删除物料
const addCheckStocks = 'quota_employee_manager_addCheckStocks' //添加盘点单
const importCheckStocks = 'quota_employee_manager_importCheckStocks' //导入盘点单
const checkStocksApprovalProcess = 'quota_employee_manager_checkStocksApprovalProcess' //查看盘点单审批流程
const confirm = Modal.confirm
const { Option } = Select
export default class ManualInventoryRecordList extends BaseListPage<
  ManualInventoryRecordListProps,
  ManualInventoryRecordListState
> {
  // 隐藏掉头曲二曲
  // public hideArr: any = ['头曲', '二曲', '泸州老窖头曲酒类销售有限公司', '泸州老窖二曲酒类销售有限公司']
  // public brandList = udMainStore.brandList.filter(item => this.hideArr.indexOf(item.title) === -1)
  public brandList = udMainStore.brandList
  protected useConditionsField = true
  private modal
  constructor(props) {
    super(props)
    this.state = {
      customerList: [],
      treeDataList: [],
      title: '手工盘点库存记录',
      selectData: {},
      loading: true,
      rowKey: 'id',
      queryApi: params => {
        return http.post(apis.queryDealerCheck, params)
      },
      method: 'POST',
      conditions: [
        {
          id: 'brandCode',
          label: '销售组织',
          render: () => (
            <Select showSearch>
              {this.brandList.map(({ value, title }) => (
                <Option key={value} value={value}>
                  {title}
                </Option>
              ))}
            </Select>
          ),
        },
        {
          id: ['inventoryBegineTime', 'inventoryEndTime'],
          label: '盘点时间',
          render: <UdDateRangePicker valueFormat={['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59']} />,
        },
        { id: 'dealerCode', label: '客户编码' },
        { id: 'dealerName', label: '客户名称' },
        { id: 'createName', label: '盘点业务人员' },
        {
          id: 'dealerType',
          label: '客户类型',
          render: () => (
            <Select placeholder="请选择状态">
              <Option value="DEALER">经销商</Option>
              <Option value="DISTRIBUTOR">分销商</Option>
            </Select>
          ),
        },
        {
          id: 'approvalStatus',
          label: '审批状态',
          render: () => (
            <Select placeholder="请选择状态">
              <Option value="AUDITING">审批中</Option>
              <Option value="AUDITSUCC">审批通过</Option>
              <Option value="AUDITFAIL">审批不通过</Option>
            </Select>
          ),
        },
        { id: 'parentCode', label: '上级客户编码' },
        { id: 'parentName', label: '上级客户名称' },
      ],
      columns: [
        { title: '盘点周期', key: 'description', dataIndex: 'description', width: 160 },
        ['客户编码', 'dealerCode'],
        {
          title: '客户类型',
          key: 'dealerType',
          dataIndex: 'dealerType',
          render: recode => <span>{recode == 'DISTRIBUTOR' ? '分销商' : recode == 'DEALER' ? '经销商' : ''}</span>,
        },
        ['客户名称', 'dealerName'],
        ['销售组织', 'brandNameShort'],
        ['所属管理区域', 'belongAreaName'],
        ['盘点业务人员', 'createName'],
        {
          title: '库存盘点附件',
          width: 100,
          dataIndex: 'stockCertificate',
          render: (text, row) => {
            const urls = row.stockCertificate ? row.stockCertificate.split(',') : []
            if (row.stockCertificate) return <WithToolbar imagesList={urls} />
          },
        },
        {
          title: '审批状态',
          width: 120,
          dataIndex: 'approvalStatus',
          render: (text, row) => {
            if (row['del'] === 'Y') {
              return <Badge color="red" text={<span style={{ fontSize: '12px' }}>已删除</span>} />
            } else {
              switch (text) {
                // 审批中
                case 'AUDITING':
                  return <Badge color="orange" text={<span style={{ fontSize: '12px' }}>审批中</span>} />
                // 审批成功
                case 'AUDITSUCC':
                  return (
                    <Badge
                      style={{ fontSize: '12px' }}
                      color="green"
                      text={<span style={{ fontSize: '12px' }}>审批通过</span>}
                    />
                  )
                // 审批失败
                case 'AUDITFAIL':
                  return (
                    <Badge
                      style={{ fontSize: '12px' }}
                      color="red"
                      text={<span style={{ fontSize: '12px' }}>审批不通过</span>}
                    />
                  )
                default:
                  return <span>--</span>
              }
            }
          },
        },
        {
          title: '操作',
          width: 200,
          render: columnRenders.operate([
            {
              auth: checkStocksApprovalProcess,
              title: '查看审批流程',
              action: (text: any, record: any) => {
                this.showStocksApprovalProcess(record)
              },
            },
            {
              show: (text: any, record: any) => {
                return record['del'] === 'N'
              },
              title: '删除',
              auth: deleteBtnAuthAll,
              action: (text: any, record: any) => {
                confirm({
                  title: '确定要删除该盘点单吗？',
                  onOk: () => {
                    return this.handleRemoveRecord(record)
                  },
                })
              },
            },
          ]),
        },
      ],
      leftBtns: [
        <Button type="primary" onClick={this.exportTableData}>
          导出
        </Button>,
        uaaApp.canUse(importCheckStocks) && (
          <Button type="primary" onClick={this.handImportExcel}>
            导入
          </Button>
        ),
        uaaApp.canUse(addCheckStocks) && (
          <Button type="primary" onClick={this.addStock}>
            新增
          </Button>
        ),
      ],
      tableProps: {
        scroll: { x: true },
        expandedRowRender: this.expandedRowRender,
        onExpand: this.onExpand,
      },
      downloading: false,
      uploading: false,
    }
  }
  render() {
    return (
      <Spin
        spinning={this.state.uploading || this.state.downloading}
        tip={this.state.uploading ? '上传中，请稍后...' : '下载中，请稍后...'}
      >
        {super.render()}
      </Spin>
    )
  }

  //新增库存盘点记录
  private addStock = () => {
    this.modal = UdModal.open({
      title: '新增盘点记录',
      content: <AddStockFormModal />,
      okText: '确定',
      cancelText: '取消',
      onOk: values => {
        UdDrawer.open({
          title: '新增库存盘点记录',
          width: '50%',
          footer: true,
          content: <AddCheckStockDetail stockForm={values} />,
          onSubmit: () => {
            console.log(`新增库存盘点记录成功~`)
            this.refresh()
          },
        })
      },
    })
  }

  //查看审批流程
  private showStocksApprovalProcess = record => {
    UdDrawer.open({
      title: '盘点记录审批流程',
      width: '40%',
      footer: false,
      content: <StocksApprovalProcess record={record} />,
    })
  }

  private handImportExcel = () => {
    UdDrawer.open({
      title: '导入',
      width: '40%',
      content: <ImportExcel />,
      onSubmit: () => {
        this.query()
      }
    })
  }

  //导出table
  private exportTableData = () => {
    this.setState({ downloading: true })
    http
      .post(
        quotaApis.downloadDealerCheckStockDetailsExcel,
        { conditions: { ...this.queryParams.conditions } },
        { responseType: 'arraybuffer' }
      )
      .then(res => {
        if (!res.data.code) {
          downBlobFileXlsx(res.data, '库存盘点记录')
        }
      })
      .finally(() => {
        this.setState({ downloading: false })
      })
  }

  private refresh = () => {
    this.setState({ loading: true })
    let id = JSON.parse(localStorage.getItem('selectParentRecord')).id
    http
      .get(apis.CheckStockListDetail, { params: { id } })
      .then(resp => {
        let value = { ...this.state.selectData }
        value[id] = resp.data
        this.setState({
          selectData: value,
        })
      })
      .finally(() => {
        this.setState({ loading: false })
      })
  }

  private onExpand = (expanded, record) => {
    if (!expanded) return null
    localStorage.setItem('historyRecord', record.id)
    localStorage.setItem('selectParentRecord', JSON.stringify(record))
    http.get(apis.CheckStockListDetail, { params: { id: record.id } }).then(resp => {
      let value = { ...this.state.selectData }
      value[record.id] = resp.data
      this.setState({
        loading: false,
        selectData: value,
      })
    })
  }
  private expandedRowRender = (recode) => {
    const columns = [
      { title: '序号', dataIndex: 'id', key: 'id', width: 50, render: (text, reoled, index) => index + 1 },
      { title: '物料编码', dataIndex: 'prodBarcode', key: 'prodBarcode', width: 100 },
      { title: '物料描述', key: 'matName', dataIndex: 'matName', width: 150 },
      { title: '期初库存(含未到货)/件', dataIndex: 'beginningRealStock', key: 'beginningRealStock', width: 146 },
      { title: '期间开单/件', dataIndex: 'nowAog', key: 'nowAog', width: 140 },
      { title: '调入调出', dataIndex: 'allocateNumber', key: 'allocateNumber', width: 100 },
      { title: '当前实物库存/件', dataIndex: 'nowRealStock', key: 'nowRealStock', width: 140 },
      { title: '当前未到货/件', dataIndex: 'onOrder', key: 'onOrder', width: 130 },
      { title: '期间动销数/件', dataIndex: 'nowMove', key: 'nowMove', width: 100 },
      { title: '下月订单计划/件', dataIndex: 'nextMonthOrderNum', key: 'nextMonthOrderNum', width: 130 },
      {
        title: '动销说明',
        dataIndex: 'nowMoveDes',
        key: 'nowMoveDes',
        width: 130,
        render: (text, record) => {
          return (
            <Tooltip title={record.nowMoveDes}>
              <div style={{ width: '130px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                {record.nowMoveDes}
              </div>
            </Tooltip>
          )
        },
      },
      {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
        width: 130,
        render: (text, record) => {
          return (
            <Tooltip title={record.remark}>
              <div style={{ width: '130px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                {record.remark}
              </div>
            </Tooltip>
          )
        },
      },
      {
        title: '操作',
        width: 100,
        render: columnRenders.operate([
          {
            title: '编辑',
            auth: editBtnAuth,
            action: (text: any, record: any) => {
              this.handleEdit(record)
            },
          },
          {
            title: '删除',
            auth: deleteBtnAuth,
            action: (text: any, record: any) => {
              confirm({
                title: '确定要删除该物料吗？',
                onOk: () => {
                  return this.handleRemove(record)
                },
              })
            },
          },
        ]),
      },
    ]

    return (
      <Spin spinning={this.state.loading}>
        <UdTable columns={columns} dataSource={this.state.selectData[recode.id]} pagination={false} rowKey="id" />
      </Spin>
    )
  }

  private handleEdit = row => {
    let selectParentRecord = JSON.parse(localStorage.getItem('selectParentRecord'))
    let { brandNameShort, dealerName, description } = selectParentRecord
    // let record = { ...row, brandNameShort, dealerName, description }
    let { id } = row;
    http.get(
      quotaApis.getCheckStockDetail, { params: { id } }).then(res => {
        let record = { ...res.data, brandNameShort, dealerName, description }
        UdDrawer.open({
          title: `编辑库存盘点数据`,
          width: '50%',
          content: <EditCheckStockDetail record={record} />,
          onSubmit: () => {
            this.refresh()
          },
        })
      })
      .finally(() => {
      
      })
  }

  //删除物料
  private handleRemove = row => {
    http
      .post(apis.DeleteStorage, [row.id])
      .then(() => {
        message.success('删除成功')
        let data = localStorage.getItem('historyRecord')
        http.get(apis.CheckStockListDetail, { params: { id: data } }).then(resp => {
          let value = { ...this.state.selectData }
          value[data] = resp.data
          this.setState({
            loading: false,
            selectData: value,
          })
        })
        this.query()
        this.forceUpdate()
      })
      .catch(() => { })
  }

  private handleRemoveRecord = row => {
    http
      .post(apis.DeleteStorageRecord, [row.id])
      .then(() => {
        message.success('删除成功')
        this.query()
      })
      .catch(() => { })
  }
}

interface ManualInventoryRecordListState extends IBaseListPageState {
  loading: boolean
  selectData: any
  downloading?: boolean
  uploading?: boolean
  customerList?: any
  treeDataList?: any
}

interface ManualInventoryRecordListProps extends IBaseListPageProps { }
